<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class OxOrganization 
{
	public $idorganization;
    public $name;
    public $description;

    private $users;
    private $users_read;
    
    private $articles;
    private $articles_read;
    
    public static function from_id($id)
    {
        $new_org = new OxOrganization();
        $new_org->load($id);
        return $new_org;
    }
    
    function __construct()
    {
		$this->clear();
	}
    
    function clear()
    {
        $this->idorganization = '';
        $this->name = null;
        $this->description = null;
        
        $this->users_read = false;
        $this->users = array();
        
        $this->articles_read = false;
        $this->articles = array();
        return $this;
    }
    
    function load($id)
    {
        $CI =& get_instance();
        
		$query = $CI->db->select('*')
                              ->from('organizations')
                              ->where('idorganization',$id)
                              ->get()->result();
		if(!$query)
        {
            $this->clear();
        }
        else
        {
            $userdata = $query[0];
            $this->idorganization = $userdata->idorganization;
            $this->name = $userdata->name;
            $this->description = $userdata->description;
        }
        return $this;
    }

    public function articles()
    {
        $CI =& get_instance();
        
        if(!$this->articles_read)
        {
            //read articles, create article objects
            $query = $CI->db->select('idarticle')
                              ->from('organizations_users')
                              ->join('articles', 'organizations_users.idorganizations_users = articles.idorganizationrole')
                              ->where('organizations_users.idorganization = ', $this->idorganization)
                              ->get()->result();
            foreach($query as $art_stub)
            {
                $this->articles[] = OxArticle::from_id($art_stub->idarticle);
            }
            $this->articles_read = true;
        }
        return $this->articles;
    }
    public function users()
    {
        $CI =& get_instance();
        if(!$this->users_read)
        {
            //read articles, create article objects
            $query = $CI->db->select('iduser, role')
                              ->from('organizations_users')
                              ->where('idorganization = ', $this->idorganization)
                              ->get()->result();
            foreach($query as $role)
            {
                $role->user = OxUser::from_id($role->iduser);
                $this->users[] = $role;
            }
            $this->users_read = true;
        }
        return $this->users;
    }
} 